package com.shengwei.truck.driver.view.ui.mine.userinfo;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.CarTwoWayBinding;
import com.shengwei.truck.driver.bean.JsonCar;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.databinding.ActivityCarInfoManageBinding;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.vm.CarInfoViewModel;

/**
 * 车辆信息页面，维护自己的车辆信息，包括车牌号，车型等。
 */
public class CarInfoManageActivity extends BaseActivity<CarInfoViewModel, ActivityCarInfoManageBinding> implements View.OnClickListener {
    protected static int REQUEST_SEL_CAR = 0;
    private String mCarId;   //车型ID
    private String mCarNum;  //车牌号
    private String mEtcNum;  //ETC号码
    private String mDurableYears; //使用年限
    private JsonCar mCar;
    private CarTwoWayBinding carTwoWayBinding;
    private int mIsEtc = 1; //0否，1是

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
        initLiveDataObersve();
    }

    /**
     * 初始化页面数据，请求“我的车辆信息”接口
     */
    private void initData() {
        mViewModel.getMyCarInfo();
    }

    /**
     * 更新 “车辆信息”页面数据
     */
    public void updatePageData(JsonCar data) {
        if(data != null) {
            mCar = data;
            if(carTwoWayBinding == null) {
                carTwoWayBinding = new CarTwoWayBinding(mCar);
            }
            carTwoWayBinding.setCar(mCar);
            mDataBinding.setCarTwoWayBinding(carTwoWayBinding);

            //在这里单独处理单选按钮，因为用databinding处理单选组的话，现在出现闪烁
            int isHasEtc = data.getEtcNumHave();
            if(isHasEtc == 1){
                mDataBinding.radioGroup.check(R.id.yesEtc);
            }
            else{
                mDataBinding.radioGroup.check(R.id.noEtc);
            }
        }
    }

    /**
     * 只更新与车型相关的附加信息，如厂商，品牌等
     * @param data
     */
    private void updateCarDetail(JsonCar data) {
        if(data != null) {
            mCar.maker = data.maker;
            mCar.setTypeId(data.id);
            mCar.name = data.name;
            mCar.brand = data.brand;
            mCar.typeCode = data.typeCode;
            mCar.capacity = data.capacity;
            mCar.axleNum = data.axleNum;
            mCar.mepFlag = data.mepFlag;
            if(carTwoWayBinding == null) {
                carTwoWayBinding = new CarTwoWayBinding(mCar);
            }
            carTwoWayBinding.setCar(mCar);
            mDataBinding.setCarTwoWayBinding(carTwoWayBinding);
        }
    }

    /**
     * 监听接口调用成功或失败，监听接口返回的数据
     */
    private void initLiveDataObersve() {

        //监听 “我的车辆信息”接口返回的数据，并填充“车辆信息”页面的显示
        mViewModel.getCarInfoPageLiveData().observe(this, new Observer<Result<JsonCar>>() {
            @Override
            public void onChanged(Result<JsonCar> carResult) {
                carResult.handler(new OnCallback<JsonCar>() {
                    @Override
                    public void onSuccess(JsonCar data) {
                        updatePageData(data);
                    }
                });
            }
        });

        //监听 “获取车辆生产厂商，品牌,国标等级等车型自带的信息” 接口返回的数据，或者调用成功，失败等
        mViewModel.getCarDetailLiveData().observe(this, new Observer<Result<JsonCar>>() {
            @Override
            public void onChanged(Result<JsonCar> result) {
                result.handler(new OnCallback<JsonCar>() {
                    @Override
                    public void onSuccess(JsonCar data) {
                        updateCarDetail(data);;
                    }
                });
            }
        });
        //监听 “提交车辆信息”接口
        mViewModel.getBindCarLiveData().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> result) {
                result.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        Intent i = new Intent();
                        i.putExtra("carNum",mCarNum);
                        setResult(RESULT_OK,i);
                        finish();
                     }
                });
            }
        });
    }

    /**
     * 初始化视图控件
     */
    private void initView() {
        mDataBinding.tvCarName.setOnClickListener(this);
        mDataBinding.btSubmit.setOnClickListener(this);
        //mDataBinding.radioGroup.check(R.id.yesEtc);
        mDataBinding.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(RadioGroup group, int checkId) {
                switch (checkId){
                    case R.id.yesEtc:
                        mIsEtc = 1;
                        break;
                    case R.id.noEtc:
                        mIsEtc = 0;
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_car_info_manage;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvCarName: //选择车辆名称（型号）
                Intent i = new Intent(this, SearchCarActivity.class);
                startActivityForResult(i,REQUEST_SEL_CAR);
                break;
            case R.id.btSubmit: //提交车辆信息
                boolean isCorrect = checkInput();
                if(isCorrect && !TextUtils.isEmpty(mCarId)) {
                    mViewModel.bindCarInfo(mCarNum,mCarId,mIsEtc,mDurableYears);
                }
                break;
        }
    }

    /**
     * 检查输入是否正常
     * “etc号码” 与 “使用年限”非必填
     */
    private boolean checkInput() {
        mCarNum = mDataBinding.edtCarNum.getText().toString(); //车牌号
        String carName = mDataBinding.tvCarName.getText().toString();              //车辆名称（或叫型号）
        String manufacturer = mDataBinding.edtManufacturer.getText().toString();  //厂家 ：从数据库中自动代入
        String brand = mDataBinding.edtCarBrand.getText().toString();             //品牌 ：从数据库中自动代入
        String carType = mDataBinding.edtCarType.getText().toString();           //类型： 从数据库中自动代入
        String loadWeight = mDataBinding.edtLoadWeight.getText().toString();     //载重： 从数据库中自动代入
        String axlesNums = mDataBinding.edtAxlesNums.getText().toString();       //车轴数量： 从数据库中自动代入
        String countryLevel = mDataBinding.edtCountryLevel.getText().toString(); //国标等级
        mDurableYears = mDataBinding.edtDurableYears.getText().toString();      //年检信息（输入年份，非必填）

        if(TextUtils.isEmpty(mCarNum)) {
            Toast.makeText(CarInfoManageActivity.this,R.string.car_num_not_empty,Toast.LENGTH_SHORT).show();
            return false;
        }
 /*       else{
            boolean isValide = CommonUtil.isVehicleNumber(mCarNum);
            if(!isValide){
                Toast.makeText(CarInfoManageActivity.this,R.string.car_num_invalide,Toast.LENGTH_SHORT).show();
                return false;
            }
        }*/

        if(TextUtils.isEmpty(carName)) {
            Toast.makeText(CarInfoManageActivity.this,R.string.car_name_not_empty,Toast.LENGTH_SHORT).show();
            return false;
        }

        if(TextUtils.isEmpty(manufacturer)) {
            Toast.makeText(CarInfoManageActivity.this,R.string.car_manufacture_not_empty,Toast.LENGTH_SHORT).show();
            return false;
        }

        if(TextUtils.isEmpty(brand)) {
            Toast.makeText(CarInfoManageActivity.this,R.string.car_brand_not_empty,Toast.LENGTH_SHORT).show();
            return false;
        }

        if(TextUtils.isEmpty(carType)) {
            Toast.makeText(CarInfoManageActivity.this,R.string.car_type_not_empty,Toast.LENGTH_SHORT).show();
            return false;
        }

        if(TextUtils.isEmpty(loadWeight)) {
            Toast.makeText(CarInfoManageActivity.this,R.string.car_load_weight_not_empty,Toast.LENGTH_SHORT).show();
            return false;
        }
        if(TextUtils.isEmpty(axlesNums)) {  //车轴数量
            Toast.makeText(CarInfoManageActivity.this,R.string.car_axlesNums_not_empty,Toast.LENGTH_SHORT).show();
            return false;
        }
        if(TextUtils.isEmpty(countryLevel)) {  //国标等级
            Toast.makeText(CarInfoManageActivity.this,R.string.country_level_not_empty,Toast.LENGTH_SHORT).show();
            return false;
        }

        mCarId = mCar.getTypeId();
        if(TextUtils.isEmpty(mCarId)) {  //车型ID
            Toast.makeText(CarInfoManageActivity.this,R.string.car_model_not_empty,Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode == REQUEST_SEL_CAR && resultCode == RESULT_OK) {
             Bundle b = data.getExtras();
             if(b != null) {
                 mCarId = b.getString("carId");
                 String carName = b.getString("carName");
                 String unit = b.getString("unit");//单位
                 if(!TextUtils.isEmpty(carName)){
                     mDataBinding.tvCarName.setText(carName);
                     mDataBinding.tvWeightUnit.setText(unit);
                     mViewModel.getCarDetail(mCarId);
                 }
             }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}